package com.fanshuai.spring.boot.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Configuration
@ConditionalOnProperty({"redis.cluster.enabled"})
public class RedisClusterConfig {
    @Bean
    public RedisConnectionFactory connectionFactory() {
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        List<RedisNode> nodeList = new ArrayList<RedisNode>();
        nodeList.add(new RedisNode("localhost", 7000));
        nodeList.add(new RedisNode("localhost", 7001));
        nodeList.add(new RedisNode("localhost", 7002));
        nodeList.add(new RedisNode("localhost", 7003));
        nodeList.add(new RedisNode("localhost", 7004));
        nodeList.add(new RedisNode("localhost", 7005));
        clusterConfiguration.setClusterNodes(nodeList);

        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(8);
        poolConfig.setMaxTotal(8);
        poolConfig.setMinIdle(1);
        poolConfig.setMaxWaitMillis(1000L);
        poolConfig.setTimeBetweenEvictionRunsMillis(100);

        LettuceClientConfiguration clientConfiguration = LettuceClientConfiguration.builder()
                .commandTimeout(Duration.ofMillis(800))
                .shutdownTimeout(Duration.ofSeconds(5))
                .build();

        return new LettuceConnectionFactory(clusterConfiguration, clientConfiguration);
    }
}
